package com.fafa.pos.util.newland;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.io.File;
import java.util.List;


/**
 * 应用程序操作工具类
 */
public class AppUtils {
	private static String TAG = "AppUtils";
	/**
	 * 获取apk安装包的信息
	 * 
	 * @param context
	 *            Context实例
	 * @param apkPath
	 *            apk的存放路径
	 */
	public static PackageInfo getAndroidArchiveInfo(Context context,
			String apkPath) {
		if (apkPath == null || "".equals(apkPath) || !apkPath.endsWith(".apk")) {
			return null;
		}
		File apkFile = new File(apkPath);
		if (apkFile == null || !apkFile.exists() || !apkFile.canRead()) {
			return null;
		}
		try {
			PackageManager pm = context.getPackageManager();
			return pm.getPackageArchiveInfo(apkPath,
					PackageManager.GET_ACTIVITIES);
		} catch (Exception e) {
			Log.e(TAG, "获取apk安装包的信息发生异常，APK路径：" + apkPath, e);
		}
		return null;
	}
	/**
	 * 检查App是否已经存在
	 * 
	 * @param context
	 *            Context实例
	 * @param pkgName
	 *            应用包名
	 */
	public static boolean isInstalled(Context context, String pkgName) {
		if (pkgName == null || "".equals(pkgName)) {
			return false;
		}
		try {
			PackageManager pm = context.getPackageManager();
			List<PackageInfo> list = pm.getInstalledPackages(0);
			if (list != null && list.size() > 0) {
				for (PackageInfo info : list) {
					if (info.packageName.equals(pkgName)) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			Log.e(TAG, "检查App是否已经存在发生异常，应用包名：" + pkgName, e);
		}
		return false;
	}
	/**
	 * 获取已安装的App的包信息
	 * 
	 * @param context
	 *            Context实例
	 * @param pkgName
	 *            应用程序包名
	 * @return
	 */
	public static PackageInfo getAndroidPackageInfo(Context context,
			String pkgName) {
		if (pkgName == null || "".equals(pkgName)) {
			return null;
		}
		try {
			PackageManager pm = context.getPackageManager();
			return pm.getPackageInfo(pkgName, 0);
		} catch (Exception e) {
			Log.e(TAG, "获取已安装的App的包信息发生异常，应用包名：" + pkgName, e);
		}
		return null;
	}	
	
}

